﻿/* $RCSFile: DownLoadManager.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.ECommerce/PageModules/Download/DownLoadManager.ascx.cs $
 * $log$
 * Revision 21 2010/08/09 11:08:11  christian.surieux
 *   Added Log comment to all .ascx .aspx .master files
 * Revision 8 2010/08/09 10:07:05  christian.surieux
 *   Added Log comment to all cs files
 */

using System;
using System.Globalization;
using System.Diagnostics;
using System.IO;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Web;
using System.Web.Configuration;
using AddonNice.Configuration.Settings;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Collections.Generic;
using System.Web.Security;
using System.Xml;
using System.Configuration;

using AddonNice;
using AddonNice.Authentication;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Configuration;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Helpers;
using AddonNice.Diagnostics;
using AddonNice.Settings;
using AddonNice.Core;

using AddonNice.CRMWrapper;
using AddonNice.CRMWrapper.Design;
using AddonNice.CRMWrapper.ECommerce;

using AddonNice.CRMImage;
using AddonNice.CRMImage.UI;

using AddonNice.ECommerce;
using AddonNice.ECommerce.Helpers;
using AddonNice.ECommerce.Design;
using AddonNice.ECommerce.UI;
using AddonNice.ECommerce.UI.WebControls;
using AddonNice.Settings.Download;
using AddonNice.Settings.ECommerce;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.Download
{
    /// <summary>
    /// Initializer class for DownLoadManager 
    /// </summary>
    public class DownLoadManagerSI : ECommerceModuleSI
    {
        public DownLoadManagerSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]DownLoadManagerSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]DownLoadManagerSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]DownLoadManagerSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);

            string extgrp                       =   pm.ExtendedResourcesGroup;

            UrlDataType udt                     =   new UrlDataType();
			SettingItemSpecial DownloadUrl      =	new SettingItemSpecial(EComStStr.DownloadUrl,udt);
			DownloadUrl.Required		        =	true;
            DownloadUrl.CouldOverride           =   false;
			DownloadUrl.Value		            =	"~/Downloads";
			DownloadUrl.Order		            =	1;
            DownloadUrl.Group                   =   SettingItemGroup.MODULE_SPECIAL_SETTINGS; // necessary to split tabs
            DownloadUrl.ExtendedGroupName       =   extgrp;
            DownloadUrl.ResourceFile            =   EComStStr.ResourceFile;
            DownloadUrl.ResourceItem            =   EComStStr.ResourceItem;
			DownloadUrl.EnglishName	            =	"Download url";
			DownloadUrl.Description	            =	"Url on server where download material is stored before being incorporated in db.";
			bSettings.AddSetting(DownloadUrl);

            AddRadGridPack(bSettings,10,extgrp);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]DownLoadManagerSI InitSettings END.",ModuleTraceSwitch.Sw.Info);
        }
    }

    public partial class DownLoadManager : ECommerceModule
    {
        Prod2DownLoadDB dwnDB   =   new Prod2DownLoadDB();

		#region Global Implementation

        public override Guid GuidID 
		{
			get
			{
				return new Guid(EComStStr.DownLoadManagerGuid);
			}
		}

		#endregion Global Implementation

        string DefaultDownloadUrl
        {
            get
            {
                return Settings[EComStStr.DownloadUrl].ToString();
            }
        }

        #region Ctor

        /// <summary>
		/// Ctor Set the properties of the module
		/// </summary>
        public DownLoadManager()
        {
            if (TraceProducts.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager Ctor enter at: {0}", DateTime.UtcNow), TraceProducts.Sw.Info);
        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
       			const string extgrp                 =   "DOWNLOADMANAGER";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new DownLoadManagerSI(bSettings,this);
        }

        #endregion Ctor

        protected void Page_Load(object sender, EventArgs e)
        {
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager Page_Load BEG IsPostBack: {0}",IsPostBack),ModuleTraceSwitch.Sw.Info);
            if ( ! IsPostBack )
            {
                // To allow stdAux to load module settings
                ExplorerWindow.NavigateUrl      =   string.Format("DownLoadExplorer.aspx?pageid={0}&Mid={1}",PageID,ModuleID); 
				//force paging according settings
				RadGrid1.AllowPaging	        =	Settings[EComStStr.Paging].ToBool();
                RadGrid1.AllowFilteringByColumn =	Settings[EComStStr.AllowFilteringByColumn].ToBool();
                RadGrid1.GroupingEnabled        =	Settings[EComStStr.GroupingEnabled].ToBool();
				if ( RadGrid1.AllowPaging )
						RadGrid1.PageSize       =   Settings[EComStStr.PageSz].ToInt();
            }
        }

        protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_ItemDataBound BEG e.Item.OwnerTableView.Name: {0}, e.Item: {1}",
                    e.Item.OwnerTableView.Name,e.Item),ModuleTraceSwitch.Sw.Info);
            if ( e.Item.OwnerTableView.Name == "Products" )
            {
                if (e.Item is GridEditFormItem )
                {
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_ItemDataBound Item: {0}, Type: {1}, IsInEditMode: {2}",
                            e.Item,e.Item.ItemType,e.Item.IsInEditMode),ModuleTraceSwitch.Sw.Info);
                    GridEditFormItem item           =   (GridEditFormItem)e.Item;
                    if ( item.IsInEditMode )
                    {
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_ItemDataBound DataItem: {0}",e.Item.DataItem.GetType()),ModuleTraceSwitch.Sw.Info);
                        // nothing to do on insert
                        if ( item.OwnerTableView.IsItemInserted )
                            return;
                        // retrieve current product name and set it in text property
                        try
                        {  
                            RadWSCombo Combo        =   (RadWSCombo)item.FindControl("CbProductId");
                            DbDataRecord rw         =   item.DataItem as DbDataRecord;
                            if (rw != null)
                            {
                                Guid pId            =   (Guid)rw["ProductId"];
                                ADNDynEProduct prod =   new ProductsCRM().GetProduct(pId);
                                if ( prod != null )
                                    Combo.Text      =   prod.name;
                                if (ModuleTraceSwitch.Sw.TraceVerbose)
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_ItemDataBound Combo.Text: {0}",Combo.Text),ModuleTraceSwitch.Sw.Info);
                            }
                        }
                        catch(Exception ex)
                        { 
                            if (ModuleTraceSwitch.Sw.TraceError)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DownLoadManager RadGrid1_ItemDataBound ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                            throw;
                        }
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine("[V]DownLoadManager RadGrid1_ItemDataBound END.",ModuleTraceSwitch.Sw.Info);
                    }
                }
                else if (e.Item is GridDataItem)
                {
                    GridDataItem item               =   e.Item as GridDataItem;
                        // retrieve current product name and set it in text property
                        try
                        {  
                            Label LbProd            =   (Label)item.FindControl("LbProductId");
                            if (ModuleTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_ItemDataBound 2 item.DataItem: {0}, LbProd null: {1}",item.DataItem,(LbProd == null )),ModuleTraceSwitch.Sw.Info);
                            DbDataRecord rw         =   item.DataItem as DbDataRecord;
                            if ((LbProd != null) && (rw != null))
                            {
                                if (ModuleTraceSwitch.Sw.TraceVerbose)
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_ItemDataBound 2 rw.FieldCount: {0}",rw.FieldCount),ModuleTraceSwitch.Sw.Info);
                                Guid pId            =   (Guid)rw["ProductId"];
                                ADNDynEProduct prod =   new ProductsCRM().GetProduct(pId);
                                if ( prod != null )
                                    LbProd.Text     =   prod.name;
                                if (ModuleTraceSwitch.Sw.TraceVerbose)
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_ItemDataBound 2 LbProd.Text: {0}",LbProd.Text),ModuleTraceSwitch.Sw.Info);
                            }
                        }
                        catch(Exception ex)
                        { 
                            if (ModuleTraceSwitch.Sw.TraceError)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DownLoadManager RadGrid1_ItemDataBound ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                            throw;
                        }
                }
            }
            else if ( e.Item.OwnerTableView.Name == "Files" )
            {
                if (e.Item is GridEditFormItem )
                {
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_ItemDataBound Item: {0}, Type: {1}, IsInEditMode: {2}",
                            e.Item,e.Item.ItemType,e.Item.IsInEditMode),ModuleTraceSwitch.Sw.Info);
                    GridEditFormItem item       =   (GridEditFormItem)e.Item;
                    if ( item.IsInEditMode )
                    {
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_ItemDataBound DataItem: {0}",e.Item.DataItem.GetType()),ModuleTraceSwitch.Sw.Info);
                        // nothing to do on insert
                        if ( item.OwnerTableView.IsItemInserted )
                            return;
                        // retrieve current field title and  isMAin flag and set values
                        try
                        {  
                            DbDataRecord rw     =   item.DataItem as DbDataRecord;
                            if (rw != null)
                            {
                                TextBox TbFileTitle         =   (TextBox)item.FindControl("TbFileTitle");  
                                if ( TbFileTitle != null )
                                    TbFileTitle.Text        =   (string)rw["VersionFileTitle"];
                                CheckBox cbFileIsMain       =   (CheckBox)item.FindControl("CbIsMain");  
                                if ( cbFileIsMain != null )
                                    cbFileIsMain.Checked    =   (bool)rw["VersionFileIsMain"];
                            }
                        }
                        catch(Exception ex)
                        { 
                            if (ModuleTraceSwitch.Sw.TraceError)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DownLoadManager RadGrid1_ItemDataBound ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                            throw;
                        }
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine("[V]DownLoadManager RadGrid1_ItemDataBound END.",ModuleTraceSwitch.Sw.Info);
                    }
                }
                else if (e.Item is GridDataItem)
                {
                    GridDataItem item   =   e.Item as GridDataItem;
                    // retrieve current field title and  isMAin flag and set values
                    try
                    {  
                        DbDataRecord rw                 =   item.DataItem as DbDataRecord;
                        if (rw != null)
                        {
                            TextBox TbFileTitle         =   (TextBox)item.FindControl("TbFileTitle");  
                            if ( TbFileTitle != null )
                                TbFileTitle.Text        =   (string)rw["VersionFileTitle"];
                            CheckBox cbFileIsMain       =   (CheckBox)item.FindControl("CbIsMain");  
                            if ( cbFileIsMain != null )
                                cbFileIsMain.Checked    =   (bool)rw["VersionFileIsMain"];
                        }
                    }
                    catch(Exception ex)
                    { 
                        if (ModuleTraceSwitch.Sw.TraceError)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DownLoadManager RadGrid1_ItemDataBound ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                        throw;
                    }
                }
            }
        }

        void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)
        {
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_DeleteCommand BEG OwnerTableView.Name: {0}",e.Item.OwnerTableView.Name),ModuleTraceSwitch.Sw.Info);
            GridDataItem dataItem   =   (GridDataItem)e.Item;
            if (e.Item.OwnerTableView.Name == "Products")
            {
                int Prod2DownLoadId = (int)dataItem.GetDataKeyValue("Prod2DownLoadId");
                try
                {
                    dwnDB.DeleteProd2DownLoad(Prod2DownLoadId);
                }
                catch (Exception ex)
                {
                    if (ModuleTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DownLoadManager RadGrid1_DeleteCommand Error deleting Prod2DownLoadId: {0}, ex: {1}", Prod2DownLoadId, ex), ModuleTraceSwitch.Sw.Info);
                    throw;
                }
                return;
            }
            else if (e.Item.OwnerTableView.Name == "Versions")
            {
                /*
                GridDataItem parentItem     = (GridDataItem)(e.Item.OwnerTableView.ParentItem);
                string strProd2DownLoadId   =   string.Empty;
                if (parentItem != null)
                {
                   strProd2DownLoadId       =   (string)(parentItem.OwnerTableView.DataKeyValues[parentItem.ItemIndex][ "Prod2DownLoadId"]);
                }

                int wProd2DownLoadId       =   int.Parse(strProd2DownLoadId);
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_DeleteCommand  strProd2DownLoadId: {0}",strProd2DownLoadId),ModuleTraceSwitch.Sw.Info);
                
                */ 
                try
                {
                    int VersionProdId           =   (int)dataItem.GetDataKeyValue("VersionProdId");
			        if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_DeleteCommand Alias: {0}",VersionProdId),ModuleTraceSwitch.Sw.Info);
                    dwnDB.DeleteVersionProd(VersionProdId);
			        if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_DeleteCommand END VersionProdId: {0}",VersionProdId),ModuleTraceSwitch.Sw.Info);
                }
                catch (Exception ex)
                {
				    if (ModuleTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DownLoadManager RadGrid1_DeleteCommand ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                    throw;
                }
            }
            else if (e.Item.OwnerTableView.Name == "Files")
            {
                /*
                GridDataItem parentItem     = (GridDataItem)(e.Item.OwnerTableView.ParentItem);
                string strProd2DownLoadId   =   string.Empty;
                if (parentItem != null)
                {
                   strProd2DownLoadId       =   (string)(parentItem.OwnerTableView.DataKeyValues[parentItem.ItemIndex][ "Prod2DownLoadId"]);
                }

                int wProd2DownLoadId       =   int.Parse(strProd2DownLoadId);
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_DeleteCommand  strProd2DownLoadId: {0}",strProd2DownLoadId),ModuleTraceSwitch.Sw.Info);
                
                */ 
                try
                {
                    int VersionFileId           =   (int)dataItem.GetDataKeyValue("VersionFileId");
			        if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_DeleteCommand VersionFileId: {0}",VersionFileId),ModuleTraceSwitch.Sw.Info);
                    dwnDB.DeleteVersionFile(VersionFileId);
			        if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_DeleteCommand END VersionFileId: {0}",VersionFileId),ModuleTraceSwitch.Sw.Info);
                }
                catch (Exception ex)
                {
				    if (ModuleTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DownLoadManager RadGrid1_DeleteCommand ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                    throw;
                }
            }

            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]DownLoadManager RadGrid1_DeleteCommand END.",ModuleTraceSwitch.Sw.Info);
        }

        byte[] LoadFile(string FilePath,ref int VersionFileSize,ref string VersionFileName)
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager LoadFile BEG FilePath: {0}", FilePath),ModuleTraceSwitch.Sw.Info);
            
            string phyPath          =   Server.MapPath(FilePath);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager LoadFile phyPath: {0}", phyPath),ModuleTraceSwitch.Sw.Info);
            byte[] BinProd          =   null;
            FileStream fs           =   null;
            try
            {
                FileInfo fi         =   new FileInfo(phyPath);
                VersionFileSize     =   (int)fi.Length;
                VersionFileName     =   fi.Name;
                BinProd             =   new Byte[fi.Length];
                if ( ModuleTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager BinProd fi.Length: {0}", fi.Length),ModuleTraceSwitch.Sw.Info);
                fs                  =   new FileStream(phyPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                fs.Read(BinProd, 0, (int)fi.Length);
            }
            catch (Exception ex)
            {
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DownLoadManager FileStream Path: {0}, ex: {1}", phyPath, ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            finally
            {
                if ( fs != null )
                    fs.Close();
            }
            return BinProd;
        }

        void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
        {
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_UpdateCommand BEG OwnerTableView.Name: {0}",e.Item.OwnerTableView.Name),ModuleTraceSwitch.Sw.Info);
            GridEditableItem editedItem     =   e.Item as GridEditableItem;
            Hashtable newValues             =   new Hashtable();
            if (e.Item.OwnerTableView.Name == "Products")
            {
                e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                {
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_UpdateCommand newValues.Count: {0}", newValues.Count), ModuleTraceSwitch.Sw.Info);
                    foreach (DictionaryEntry ob in newValues)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_UpdateCommand ob: {0}", ob.Value), ModuleTraceSwitch.Sw.Info);
                }
                try
                {
                    string ShortDescription     =   (string)newValues["ShortDescription"];
                    bool ForEverybody           =   (bool)newValues["ForEverybody"]; // beware this is real boolean not string !!!
                    bool Locked                 =   (bool)newValues["Locked"]; // beware this is real boolean not string !!!
                    int Prod2DownLoadId         =   (int)editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["Prod2DownLoadId"];
			        if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_UpdateCommand Prod2DownLoadId: {0}",Prod2DownLoadId),ModuleTraceSwitch.Sw.Info);
                    dwnDB.UpdateProd2DownLoad(Prod2DownLoadId,ShortDescription,ForEverybody,Locked);
			        if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_UpdateCommand END Prod2DownLoadId: {0}, ShortDescription: {1}",Prod2DownLoadId,ShortDescription),ModuleTraceSwitch.Sw.Info);
                }
                catch (Exception ex)
                {
				    if (ModuleTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DownLoadManager RadGrid1_UpdateCommand ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                    throw;
                }
            }
            else if (e.Item.OwnerTableView.Name == "Versions")
            {
                e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
                try
                {
                    string Version          =   (string)newValues["Version"];
                    DateTime VersionDate    =   DateTime.Parse((string)newValues["VersionDate"]);
                    string WhatsNew         =   (string)newValues["WhatsNew"];
                    int VersionProdId       =   (int)editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["VersionProdId"];
                    GridDataItem parentItem =   (GridDataItem)(e.Item.OwnerTableView.ParentItem);
                    int Prod2DownLoadId     =   (int)(parentItem.OwnerTableView.DataKeyValues[parentItem.ItemIndex]["Prod2DownLoadId"]);
			        if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_UpdateCommand VersionProdId: {0}, Prod2DownLoadId: {1}, Version: {2}",VersionProdId,Prod2DownLoadId,Version),ModuleTraceSwitch.Sw.Info);
                    dwnDB.UpdateVersionProd(VersionProdId,Prod2DownLoadId,Version,VersionDate,WhatsNew);
			        if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_UpdateCommand END VersionProdId: {0}, Prod2DownLoadId: {1}",VersionProdId,Prod2DownLoadId),ModuleTraceSwitch.Sw.Info);
                }
                catch (Exception ex)
                {
				    if (ModuleTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DownLoadManager RadGrid1_UpdateCommand ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                    throw;
                }
                return;
            }
            else if (e.Item.OwnerTableView.Name == "Files")
            {
                GridDataItem parentVersionItem  = (GridDataItem)(e.Item.OwnerTableView.ParentItem);
                int VersionProdId               =   (int)(parentVersionItem.OwnerTableView.DataKeyValues[parentVersionItem.ItemIndex][ "VersionProdId"]);
			    if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_UpdateCommand VersionProdId: {0}",VersionProdId),ModuleTraceSwitch.Sw.Info);
                //e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
                int VersionFileId           =   (int)e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["VersionFileId"];
                GridEditableItem editItem   =   (GridEditableItem)e.Item;  
                TextBox TbFileTitle         =   (TextBox)editItem.FindControl("TbFileTitle");  
                string VersionFileTitle     =   TbFileTitle.Text.Trim();;
                TextBox TbFilePath          =   (TextBox)editItem.FindControl("TbFilePath");  
                string FilePath             =   TbFilePath.Text.Trim();
                CheckBox cbFileIsMain       =   (CheckBox)editItem.FindControl("CbIsMain");  
                bool VersionFileIsMain      =   cbFileIsMain.Checked;
		        if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_UpdateCommand VersionFileTitle: {0}, FilePath: {1}",VersionFileTitle,FilePath),ModuleTraceSwitch.Sw.Info);
                try
                {

                    if ( !string.IsNullOrEmpty(FilePath) )
                    {
                        string VersionFileName      =   string.Empty;
                        int VersionFileSize         =   0;
                        byte[] BinProd              =   LoadFile(FilePath,ref VersionFileSize,ref VersionFileName);
                        dwnDB.UpdateVersionFile(VersionFileId,VersionProdId,VersionFileTitle,VersionFileIsMain,VersionFileSize,VersionFileName,BinProd);
			            if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_UpdateCommand updated VersionFileName: {0}, FilePath: {1}",VersionFileName,FilePath),ModuleTraceSwitch.Sw.Info);
                    }
                    else
                    {
                        dwnDB.UpdateVersionFile(VersionFileId,VersionProdId,VersionFileTitle,VersionFileIsMain);
			            if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_UpdateCommand updated VersionFileName: {0}",VersionFileTitle,FilePath),ModuleTraceSwitch.Sw.Info);
                    }

			        if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_UpdateCommand END VersionFileId: {0}",VersionFileId),ModuleTraceSwitch.Sw.Info);
                }
                catch (Exception ex)
                {
				    if (ModuleTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DownLoadManager RadGrid1_UpdateCommand ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                    throw;
                }
            }
        }

        private void RadGrid1_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_InsertCommand BEG OwnerTableView.Name: {0}",e.Item.OwnerTableView.Name),ModuleTraceSwitch.Sw.Info);
            GridEditableItem editedItem         =   e.Item as GridEditableItem;
            if (e.Item.OwnerTableView.Name == "Products")
            {
                Hashtable newValues             =   new Hashtable();
                e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                {
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_InsertCommand newValues.Count: {0}", newValues.Count), ModuleTraceSwitch.Sw.Info);
                    foreach (DictionaryEntry ob in newValues)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_InsertCommand ob: {0}", ob.Value), ModuleTraceSwitch.Sw.Info);
                }
                try
                {
                    GridEditableItem editItem   =   (GridEditableItem)e.Item;  
                    RadWSCombo Combo            =   (RadWSCombo)editItem.FindControl("CbProductId");  
                    Guid ProductId              =   new Guid(Combo.SelectedValue);
                    string ShortDescription     =   (string)newValues["ShortDescription"];
                    bool ForEverybody           =   (bool)newValues["ForEverybody"]; // beware this is real boolean not string !!!
                    bool Locked                 =   (bool)newValues["Locked"];
			        if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_InsertCommand ProductId: {0}",ProductId),ModuleTraceSwitch.Sw.Info);
                    dwnDB.AddProd2DownLoad(ProductId,ShortDescription,ForEverybody,Locked);
			        if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_InsertCommand END Prod2DownLoadId: {0}, ShortDescription: {1}",ProductId,ShortDescription),ModuleTraceSwitch.Sw.Info);
                }
                catch (Exception ex)
                {
				    if (ModuleTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DownLoadManager RadGrid1_InsertCommand ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                    throw;
                }
            }
            else if ( e.Item.OwnerTableView.Name == "Versions" )
            {
                GridDataItem parentItem     =   (GridDataItem)(e.Item.OwnerTableView.ParentItem);
                int Prod2DownLoadId         =   (int)(parentItem.OwnerTableView.DataKeyValues[parentItem.ItemIndex][ "Prod2DownLoadId"]);
			    if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_InsertCommand Prod2DownLoadId: {0}",Prod2DownLoadId),ModuleTraceSwitch.Sw.Info);
                Hashtable newValues         =   new Hashtable();
                e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
                try
                {
                    string VersionTxt       =   (string)newValues["Version"];
                    DateTime VersionDate    =   DateTime.Parse((string)newValues["VersionDate"]);
                    string WhatsNew         =   (string)newValues["WhatsNew"];
			        if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_InsertCommand VersionTxt: {0}, WhatsNew: {1}",VersionTxt,WhatsNew),ModuleTraceSwitch.Sw.Info);
                    dwnDB.AddVersionProd(Prod2DownLoadId,VersionTxt,VersionDate,WhatsNew);
			        if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_InsertCommand END Prod2DownLoadId: {0}, Version: {1}",Prod2DownLoadId,VersionTxt),ModuleTraceSwitch.Sw.Info);
                }
                catch (Exception ex)
                {
				    if (ModuleTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DownLoadManager RadGrid1_InsertCommand ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                    throw;
                }
            }
            else if ( e.Item.OwnerTableView.Name == "Files" )
            {
                GridDataItem parentItem     =   (GridDataItem)(e.Item.OwnerTableView.ParentItem);
                int VersionProdId           =   (int)(parentItem.OwnerTableView.DataKeyValues[parentItem.ItemIndex][ "VersionProdId"]);
			    if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_InsertCommand VersionProdId: {0}",VersionProdId),ModuleTraceSwitch.Sw.Info);
//                Hashtable newValues         =   new Hashtable();
//                e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);

                try
                {
                    GridEditableItem editItem   =   (GridEditableItem)e.Item;  
                    TextBox TbFileTitle         =   (TextBox)editItem.FindControl("TbFileTitle");  
                    string VersionFileTitle     =   TbFileTitle.Text.Trim();
                    TextBox TbFilePath          =   (TextBox)editItem.FindControl("TbFilePath");  
                    string FilePath             =   TbFilePath.Text.Trim();
                    CheckBox cbFileIsMain       =   (CheckBox)editItem.FindControl("CbIsMain");  
                    bool VersionFileIsMain      =   cbFileIsMain.Checked;
		            if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_InsertCommand VersionFileTitle: {0}, FilePath: {1}",VersionFileTitle,FilePath),ModuleTraceSwitch.Sw.Info);

                    if ( !string.IsNullOrEmpty(FilePath) )
                    {
                        string VersionFileName      =   string.Empty;
                        int VersionFileSize         =   0;
                        byte[] BinProd              =   LoadFile(FilePath,ref VersionFileSize,ref VersionFileName);
                        dwnDB.AddVersionFile(VersionProdId,VersionFileTitle,VersionFileIsMain,VersionFileSize,VersionFileName,BinProd);
		                if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_InsertCommand inserted VersionFileName: {0}, FilePath: {1}",VersionFileName,FilePath),ModuleTraceSwitch.Sw.Info);
                    }
                    else
                    {
                        dwnDB.AddVersionFile(VersionProdId,VersionFileTitle,VersionFileIsMain,0,string.Empty,new byte[0]);
			            if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_InsertCommand inserted VersionFileName: {0}",VersionFileTitle,FilePath),ModuleTraceSwitch.Sw.Info);
                    }
			        if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_InsertCommand END VersionProdId: {0}",VersionProdId),ModuleTraceSwitch.Sw.Info);
                }
                catch (Exception ex)
                {
				    if (ModuleTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DownLoadManager RadGrid1_InsertCommand ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                    throw;
                }
            }
        }
        
        void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_ItemCommand CommandName: {0}, SelectedIndexes.Count: {1}",
                    e.CommandName,RadGrid1.SelectedIndexes.Count),ModuleTraceSwitch.Sw.Info);
        }

        protected void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_NeedDataSource BEG e.IsFromDetailTable: {0}",
                    e.IsFromDetailTable),ModuleTraceSwitch.Sw.Info);
            if (!e.IsFromDetailTable)
            {
                RadGrid1.DataSource         =   dwnDB.GetAllProd2DownLoad();
            }
        }

        protected void RadGrid1_DetailTableDataBind(object source, Telerik.Web.UI.GridDetailTableDataBindEventArgs e)
        {
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_DetailTableDataBind BEG e.DetailTableView.Name: {0}",
                    e.DetailTableView.Name),ModuleTraceSwitch.Sw.Info);
            GridDataItem dataItem                       =   (GridDataItem)e.DetailTableView.ParentItem;
            switch (e.DetailTableView.Name)
            {
                case "Versions":
                    {
                        int Prod2DownLoadId             =   (int)dataItem.GetDataKeyValue("Prod2DownLoadId");
			            if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_DetailTableDataBind Prod2DownLoadId: {0}",
                                Prod2DownLoadId),ModuleTraceSwitch.Sw.Info);
                        e.DetailTableView.DataSource    =   dwnDB.GetVersionProdByDownloadId(Prod2DownLoadId);
                        break;
                    }

                case "Files":
                    {
                        int VersionProdId               =   (int)dataItem.GetDataKeyValue("VersionProdId");
			            if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadManager RadGrid1_DetailTableDataBind VersionProdId: {0}",
                                VersionProdId),ModuleTraceSwitch.Sw.Info);
                        e.DetailTableView.DataSource    =   dwnDB.GetVersionFileByVersion(VersionProdId);
                        break;
                    }
            }
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]DownLoadManager RadGrid1_DetailTableDataBind END.",ModuleTraceSwitch.Sw.Info);
        }

        #region Std overrides 

        /// <summary>
        /// Triggered from Page.OnPreInit
        /// We must set the Add button before buttons are initialized by base method
        public override void Page_PreInit(object sender, EventArgs e)
        {
            base.Page_PreInit(sender, e);
            string strcult              =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
        }

		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}

		private void InitializeComponent()
		{
            Load                            +=  new EventHandler(Page_Load);
            RadGrid1.NeedDataSource         +=  new GridNeedDataSourceEventHandler(RadGrid1_NeedDataSource);
            RadGrid1.DetailTableDataBind    +=  new GridDetailTableDataBindEventHandler(RadGrid1_DetailTableDataBind);
            RadGrid1.DeleteCommand          +=  new GridCommandEventHandler(RadGrid1_DeleteCommand);
            RadGrid1.ItemCommand            +=  new GridCommandEventHandler(RadGrid1_ItemCommand);
            RadGrid1.InsertCommand          +=  new GridCommandEventHandler(RadGrid1_InsertCommand);
            RadGrid1.UpdateCommand          +=  new GridCommandEventHandler(RadGrid1_UpdateCommand);
            RadGrid1.ItemDataBound          +=  new GridItemEventHandler(RadGrid1_ItemDataBound);
 		}

        #endregion
    }
}